# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import ValidationError


class Workshop(models.Model):
    """车间模型"""
    _name = 'device.workshop'
    _description = '车间管理'
    _order = 'sequence, name'
    _rec_name = 'name'
    _inherit = ['device.permission.mixin']
    
    name = fields.Char('车间名称', required=True)
    code = fields.Char('车间编码', required=True)
    description = fields.Text('车间描述')
    
    # 关联部门
    department_id = fields.Many2one('device.department', '所属部门', required=True)
    
    # 负责人
    manager_id = fields.Many2one('device.user', '车间负责人')
    phone = fields.Char('联系电话')
    
    # 位置信息
    location = fields.Char('车间位置')
    area = fields.Float('车间面积', help='单位：平方米')
    
    # 基础信息
    sequence = fields.Integer('排序', default=10)
    status = fields.Boolean('状态', default=True)
    
    # 附件URL字段 - 存储通过公共上传接口上传的文件URL
    attachment_urls = fields.Text('附件URL列表', help='存储文件URL，多个URL用换行分隔')
    layout_image_url = fields.Char('车间布局图URL', help='车间布局图片的URL')
    safety_manual_url = fields.Char('安全手册URL', help='车间安全手册文件的URL')
    photo_urls = fields.Text('车间图片URL', help='车间现场图片的URL，多个URL用换行分隔')
    
    # 创建和修改信息
    create_time = fields.Datetime('创建时间', default=fields.Datetime.now)
    update_time = fields.Datetime('更新时间', default=fields.Datetime.now)
    create_by = fields.Char('创建者')
    update_by = fields.Char('更新者')
    remark = fields.Text('备注')
    
    # 统计字段
    device_count = fields.Integer('设备数量', compute='_compute_device_count')
    
    @api.depends()
    def _compute_device_count(self):
        for workshop in self:
            workshop.device_count = self.env['device.equipment'].search_count([
                ('workshop_id', '=', workshop.id)
            ])
    
    @api.constrains('code')
    def _check_code_unique(self):
        for record in self:
            if self.search_count([('code', '=', record.code), ('id', '!=', record.id)]) > 0:
                raise ValidationError(f'车间编码 {record.code} 已存在，请使用其他编码。')
    
    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['create_time'] = fields.Datetime.now()
            if self.env.user:
                vals['create_by'] = self.env.user.name
        return super().create(vals_list)
    
    def write(self, vals):
        vals['update_time'] = fields.Datetime.now()
        if self.env.user:
            vals['update_by'] = self.env.user.name
        return super().write(vals)
